package com.xyz.study.player;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * PlayManager实现类
 * @author XYZ
 * @version 1.0
 * @since 2021/10/18
 */
public class PlayerManagerImpl implements PlayerManager {

    /**
     * 系统中玩家容器
     */
    private volatile ConcurrentHashMap<String, Player> players = new ConcurrentHashMap<>();

    public PlayerManagerImpl(){
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
        executorService.scheduleAtFixedRate(new DeleteOfflinePlayerTask(), 60, 60, TimeUnit.SECONDS);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public synchronized void addPlayer(Player player) {
        players.putIfAbsent(player.getUsername(), player);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public synchronized Player getPlayer(String username) {
        return players.get(username);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public synchronized void broadcast(String message) {
        for (Map.Entry<String, Player> playerEntry : players.entrySet()){
            Player player = playerEntry.getValue();
            player.write(message);
        }
    }

    /**
     * 删除不在线玩家任务
     */
    private class DeleteOfflinePlayerTask implements Runnable{
        /**
         * 每分钟广播一条消息，并删除离线玩家
         */
        @Override
        public void run() {
            // 删除离线玩家
            for (Map.Entry<String, Player> playerEntry : players.entrySet()){
                Player player = playerEntry.getValue();
                if (player.isOffline()){
                    players.remove(player.getUsername());
                    broadcast("delete offline player " + player.getUsername());
                }else {
                    System.out.println("current online player " + player.getUsername());
                }
            }
            System.out.println("-------------------------------------------------------");
        }
    }


}
